import json
from django.core.paginator import Paginator
from datetime import datetime
from django.db import transaction
from django.db.models import Count
from django.db.models import Q

from django.http import JsonResponse
from django.http.response import HttpResponseRedirect
from django.shortcuts import render
# from settings import DJANGO_CONF_MODULE
from .models import *
from blueapps import account
from django.contrib.auth.models import User

def login(request):
    """
    登录页面
    """
    return render(request, 'volunteer/login.html')


# 注册
def register(request):
    try:
        username = request.POST.get("username")
        password = request.POST.get("password")
        role = request.POST.get("role")

        user = {
            "username": username,
            "password": password,
            "role": role
        }
        if int(role) == 0:
            if Student.objects.filter(username = username):
                return JsonResponse({"result": False, "code":101,"message": '注册失败，该用户名已经注册'})
            else:
                Student.objects.create(**user)
        elif int(role) == 1:
            if Company.objects.filter(username = username):
                return JsonResponse({"result": False, "code":101,"message": '注册失败，该用户名已经注册'})
            else:
                Company.objects.create(**user)
       
    except Exception as err:
        result = False
        message = str(err)
    else:
        result = True
        message = "注册成功！"
    return JsonResponse({"result": result, "message": message})




# 用户验证
def login_authentication(request):
    username = request.POST.get("username")
    password = request.POST.get("password")
    role = request.POST.get("role")
    user = {
        "username": username,
        "password": password,
        "role": role,
    }
    try:
        if int(role) == 0:
            result0 = Student.objects.filter(**user)
            if result0.exists():
                return JsonResponse({
                    "result": True, "code": 200, "message": '登录成功，点击确定跳转至主页！', 
                })
            else:
                return JsonResponse({"result": False, "code": 101, "message": '用户名或密码错误',})
        elif int(role) == 1:
            result1 = Company.objects.filter(**user)
            if result1.exists():
                return JsonResponse({
                    "result": True, "code": 200, "message": '登录成功，点击确定跳转至主页！',
                })
            else:
                return JsonResponse({"result": False, "code": 101, "message": '用户名或密码错误'})
        elif int(role) == 2:
            result2 = Manager.objects.filter(**user)
            if result2.exists():
                return JsonResponse({
                    "result": True, "code": 200, "message": '登录成功，点击确定跳转至主页！', 
                })
            else:
                return JsonResponse({"result": False, "code": 101, "message": '用户名或密码错误'})
    except Exception as error:
        print(error)
    else:
        return JsonResponse({"result": False, "code": 101, "message": '登录失败！'})

def studentHome(request):
    """
    学生主页面
    """
    return render(request, 'volunteer/student/index.html')

def companyHome(request):
    """
    公益企业主页面
    """
    return render(request, 'volunteer/company/index.html')
def checkApply(request):
    """
    审核活动页面
    """
    return render(request, 'volunteer/company/checkApply.html')


def summaryActivity(request):
    """
    活动汇总页面
    """
    return render(request, 'volunteer/manager/summaryActivity.html')

def userManagement(request):
    """
    用户管理页面
    """
    return render(request, 'volunteer/manager/userManagement.html')


def myApply(request):
    """
    我的报名页面
    """
    return render(request, 'volunteer/student/myApply.html')


# 获取报名信息表
def get_apply_list(request):
    """
    报名列表数据
    """
    applys = Apply.objects.all()
    total = len(applys)

    result_data = []
    for apply_item in applys:
        result_data.append(
            {
                "id": apply_item.id,
                "belonging_activity": apply_item.belonging_activity.publish_activity_name,
                "apply_name": apply_item.apply_name,
                "apply_age": apply_item.apply_age,
                "apply_sex": apply_item.get_apply_sex_display(),
                "apply_school": apply_item.apply_school,
                "apply_grade": apply_item.get_apply_grade_display(),
                "apply_time": apply_item.apply_time.strftime("%Y-%m-%d %H:%M:%S"),
                "apply_status": apply_item.get_apply_status_display(),
            }
        )
    return JsonResponse(
        {
            "result": True, "code": 200,
            "data": {
                "info": {
                    'data': result_data,
                    "recordsTotal": total,
                    "recordsFiltered": total,
                }
            }
        }
    )


# 获取下拉框报名活动列表数据接口
def get_activity_select_data(request):
    """
    获取下拉框所属组织值
    """
    result = []
    activity_name_data = Activity.objects.values("id", "publish_activity_name")
    for activity_name_obj in activity_name_data:
        result.append(
            {"id": activity_name_obj["id"], "text": activity_name_obj["publish_activity_name"]})

    return JsonResponse({"result": True, "code": 200, "data": {"results": result}})


# 公益活动列表，获取公益活动数据列表及查询接口
def get_activity_list(request):
    """
    获取公益活动信息列表数据
    """
    # 查询
    kwargs = {}
    # 通过发布企业名称查询
    if request.POST.get("search_publish_company_name", ""):
        kwargs.update({"publish_company_name__contains": request.POST.get(
            "search_publish_company_name")})
    # 通过地点查询
    if request.POST.get("search_publish_location", ""):
        kwargs.update(
            {"publish_location__contains": request.POST.get("search_publish_location")})
    # 通过活动名称查询
    if request.POST.get("search_publish_activity_name", ""):
        kwargs.update({"publish_activity_name__contains": request.POST.get(
            "search_publish_activity_name")})
    # 通过活动要求查询
    if request.POST.get("search_publish_demand", ""):
        kwargs.update(
            {"publish_demand__contains": request.POST.get("search_publish_demand")})

    activities = Activity.objects.filter(**kwargs)
    total = len(activities)

   

    result_data = []
    for activity_item in activities:

        apply_activity = Activity.objects.get(publish_activity_name = activity_item.publish_activity_name)
        apply_person_num = apply_activity.apply_set.all().count()
        pass_person_num = apply_activity.apply_set.filter(apply_status = ApplyStatus.PASS).count()
        Activity.objects.filter(publish_activity_name = activity_item.publish_activity_name).update(apply_person_num=apply_person_num,pass_person_num=pass_person_num)
        result_data.append(
            {
                "id": activity_item.id,
                "publish_company_name": activity_item.publish_company_name,
                "publish_demand": activity_item.publish_demand,
                "publish_activity_name": activity_item.publish_activity_name,
                "publish_datetime": activity_item.publish_datetime,
                "publish_location": activity_item.publish_location,
                "publish_person_num": activity_item.publish_person_num,
                "apply_person_num": activity_item.apply_person_num,
                "apply_person_num": activity_item.apply_person_num,
                "pass_person_num": activity_item.pass_person_num,
            }
        )
    return JsonResponse(
        {
            "result": True, "code": 200,
            "data": {
                "info": {
                    'data': result_data,
                    "activitiesTotal": total,
                    "activitiesFiltered": total,
                }
            }
        }
    )


# 保存发布信息后台接口
def save_publish_info(request):
    """
    保存发布活动数据
    """
    try:
        publish_company_name = request.POST.get("publish_company_name")
        publish_demand = request.POST.get("publish_demand")
        publish_activity_name = request.POST.get("publish_activity_name")
        publish_datetime = request.POST.get("publish_datetime")
        publish_location = request.POST.get("publish_location")
        publish_person_num = request.POST.get("publish_person_num")

        kwargs = {
            "publish_company_name": publish_company_name,
            "publish_demand": publish_demand,
            "publish_activity_name": publish_activity_name,
            "publish_datetime": publish_datetime,
            "publish_location": publish_location,
            "publish_person_num": publish_person_num,

        }
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "参数获取错误"})

    publish_id = request.POST.get("publish_id", None)

    # 添加数据
    try:
        Activity.objects.create(**kwargs)
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "保存数据错误"})
    return JsonResponse({"result": True, "code": 200, "message": "success"})

# 点击报名后台接口
def save_apply_info(request):
    """
    保存报名信息
    """
    # import pdb
    # pdb.set_trace()
    try:
        belonging_activity = int(request.POST.get('belonging_activity'))
        apply_name = request.POST.get('apply_name')
        apply_age = int(request.POST.get('apply_age'))
        apply_sex = int(request.POST.get('apply_sex'))
        apply_school = request.POST.get('apply_school')
        apply_grade = int(request.POST.get('apply_grade'))
        kwargs = {
            "belonging_activity": Activity.objects.get(id=belonging_activity),
            "apply_name": apply_name,
            "apply_age": apply_age,
            "apply_sex": apply_sex,
            "apply_school": apply_school,
            "apply_grade": apply_grade,
        }

    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "参数获取错误"})

    apply_id = request.POST.get("apply_id", None)

    # 编辑数据
    if apply_id:
        if Apply.objects.get(id=int(apply_id)).apply_status == 1:
            return JsonResponse({"result": False, "code":101, "message": "您的报名信息已经通过审核，不可以进行修改！"})
        elif Apply.objects.get(id=int(apply_id)).apply_status == 2:
            return JsonResponse({"result": False, "code": 101, "message": "您的报名信息未通过审核，不可以进行修改！"})
        else:
            # try:
            Apply.objects.filter(id=apply_id).update(**kwargs)
            return JsonResponse({"result": True, "code": 200, "message": "修改成功，等待审核!"})
            # except Exception:
            #     return JsonResponse({"result": False, "code": 101, "message": "修改报名信息错误"})

    else:
        # 添加数据
        try:
            Apply.objects.create(**kwargs)
        except Exception:
            return JsonResponse({"result": False, "code": 101, "message": "保存数据错误"})

        return JsonResponse({"result": True, "code": 200, "message": "报名成功，等待审核!"})

# 通过审核，报名状态变为PASS
# 不通过，报名状态变为FAIL
def switch_apply_status(request):
    """
    审核报名信息
    """
    action = request.POST.get("action", "")
    apply_id = request.POST.get("id", "")

    try:
        if not apply_id:
            return JsonResponse({"result": False, "code": 101, "message": "获取审核数据错误"})
        if action == "1":
            Apply.objects.filter(id=int(apply_id)).update(
                apply_status=ApplyStatus.PASS)
        elif action == "2":
            Apply.objects.filter(id=int(apply_id)).update(
                apply_status=ApplyStatus.FAIL)
        else:
            return JsonResponse({"result": False, "code": 101, "message": "审核错误，无法执行审核操作"})
        return JsonResponse({"result": True, "code": 200, "message": "审核成功！", "data": {}})
    except Exception as error:
        print(error)

# 显示活动详情后台接口
def get_activity_display_info_by_id(request, activity_id):
    """
    获取显示的数据
    """
    try:
        activity_item = Activity.objects.get(id=int(activity_id))
        return JsonResponse(
            {
                "result": True, "code": 200,
                "data": {
                    "info": {
                        'data': {
                            "id": activity_item.id,
                            "publish_company_name": activity_item.publish_company_name,
                            "publish_demand": activity_item.publish_demand,
                            "publish_activity_name": activity_item.publish_activity_name,
                            "publish_datetime": activity_item.publish_datetime,
                            "publish_location": activity_item.publish_location,
                            "publish_person_num": activity_item.publish_person_num,
                            "create_time": activity_item.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                        }
                    }
                }
            }
        )
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "获取数据失败"})


# 获取需要编辑的报名数据接口
def get_apply_info_by_id(request, apply_id):
    """
    获取编辑的数据
    """
    try:
        apply_item = Apply.objects.get(id=int(apply_id))
        return JsonResponse(
            {
                "result": True, "code": 200,
                "data": {
                    "info": {
                        'data': {
                            "id": apply_item.id,
                            "belonging_activity": apply_item.belonging_activity.id,
                            "apply_name": apply_item.apply_name,
                            "apply_age": apply_item.apply_age,
                            "apply_sex": apply_item.apply_sex,
                            "apply_school": apply_item.apply_school,
                            "apply_grade": apply_item.apply_grade,
                            "apply_status": apply_item.apply_status,
                        }
                    }
                }
            }
        )
        
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "获取数据失败"})


#获取学生用户信息表
def get_student_info_list(request):
    """
    用户信息数据
    """
    users = Student.objects.all()
    total = len(users)

    result_data = []
    for user in users:
        result_data.append(
            {
                "id": user.id,
                "username": user.username,
                "password": user.password,
                "role": user.get_role_display(),
                "create_time": user.created.strftime("%Y-%m-%d %H:%M:%S"),
            }
        )
    return JsonResponse(
        {
            "result": True, "code": 200,
            "data": {
                "info": {
                    'data': result_data,
                    "recordsTotal": total,
                    "recordsFiltered": total,
                }
            }
        }
    )

#获取公益企业用户信息表
def get_company_info_list(request):
    """
    用户信息数据
    """
    users = Company.objects.all()
    total = len(users)

    result_data = []
    for user in users:
        result_data.append(
            {
                "id": user.id,
                "username": user.username,
                "password": user.password,
                "role": user.get_role_display(),
                "create_time": user.created.strftime("%Y-%m-%d %H:%M:%S"),
            }
        )
    return JsonResponse(
        {
            "result": True, "code": 200,
            "data": {
                "info": {
                    'data': result_data,
                    "recordsTotal": total,
                    "recordsFiltered": total,
                }
            }
        }
    )

# 删除活动后台接口
def delete_activity_info(request, activity_id):
    """
    删除数据
    """
    try:
        with transaction.atomic():
            activity = Activity.objects.get(id=int(activity_id))
            activity.delete()
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "删除数据失败"})
    return JsonResponse(
        {
            "result": True, "code": 200,
            "message": "success"
        }
    )


# 注销学生账户后台接口
def delete_student_info(request, student_id):
    """
    删除数据
    """
    try:
        with transaction.atomic():
            student_user = Student.objects.get(id=int(student_id))
            student_user.delete()
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "删除数据失败"})
    return JsonResponse(
        {
            "result": True, "code": 200,
            "message": "success"
        }
    )

# 注销公益企业账户后台接口
def delete_company_info(request, company_id):
    """
    删除数据
    """
    try:
        with transaction.atomic():
            company_user = Company.objects.get(id=int(company_id))
            company_user.delete()
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "删除数据失败"})
    return JsonResponse(
        {
            "result": True, "code": 200,
            "message": "success"
        }
    )


# 重置学生账户密码后台接口
def reset_student_password(request, student_id):
    """
    重置密码
    """
    try:
        with transaction.atomic():
            student_user = Student.objects.get(id=int(student_id))
            student_user.password = '123456'
            student_user.save()
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "重置密码失败失败"})
    return JsonResponse(
        {
            "result": True, "code": 200,
            "message": "success"
        }
    )

# 重置公益企业账户密码后台接口
def reset_company_password(request, company_id):
    """
    重置密码
    """
    try:
        with transaction.atomic():
            company_user = Company.objects.get(id=int(company_id))
            company_user.password = '123456'
            company_user.save()
    except Exception:
        return JsonResponse({"result": False, "code": 101, "message": "重置密码失败失败"})
    return JsonResponse(
        {
            "result": True, "code": 200,
            "message": "success"
        }
    )
